package studykana.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import studykana.database.AppData;
import studykana.database.Databasehandler;
import studykana.models.Alphabet;
import toan.da.com.vn.R;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.TextView;

@SuppressLint("HandlerLeak")
public class TracNghiemActivity extends Activity {

	Databasehandler db;
	List<Alphabet> mlistAlphabet;

	List<String> listQuestion;
	List<String> listAnswer;
	private static final Random r = new Random();

	/*
	 * menu = 0 : Hiragana - Romaji menu = 1 : Romaji - Hiragana menu = 2
	 * :Katakana - Romaji menu = 3 : Romaji - Katakana menu = 4 : Hiragana
	 * -Katakana menu = 5 : Katakana - Hiragana
	 */
	private int menu;

	// Have 3 levels.
	private boolean[] level;

	private Alphabet mAlphabet;

	// 4 options for user choice answer.
	private Button btn1;
	private Button btn2;
	private Button btn3;
	private Button btn4;

	private Button btnQuestion;
	private TextView tvMessage;
	private List<Button> lstButtonAns;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.trac_nghiem_activity);
		ActionBar actionBar = getActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);
		level = new boolean[] { true, false, false };
		db = new Databasehandler(this);

		btn1 = (Button) findViewById(R.id.btnAns1);
		btn2 = (Button) findViewById(R.id.btnAns2);
		btn3 = (Button) findViewById(R.id.btnAns3);
		btn4 = (Button) findViewById(R.id.btnAns4);

		btnQuestion = (Button) findViewById(R.id.btnQuestion);
		tvMessage = (TextView) findViewById(R.id.tvMessage);
		onCreateView();

		btn1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				// check answer true or false.
				if (compareAnswer(btn1.getText().toString())) {
					onCreateView();
				} else {
					// if answer failed, show message
					DisplayMessage();
				}
			}
		});

		btn2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				if (compareAnswer(btn2.getText().toString())) {
					onCreateView();
				} else {
					DisplayMessage();
				}
			}
		});

		btn3.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				if (compareAnswer(btn3.getText().toString())) {
					onCreateView();
				} else {
					DisplayMessage();
				}
			}
		});

		btn4.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				if (compareAnswer(btn4.getText().toString())) {
					onCreateView();
				} else {
					DisplayMessage();
				}
			}
		});
	}

	private void setMyListAlphabet(boolean[] level) {
		mlistAlphabet = new ArrayList<Alphabet>();
		if (level[0]) {
			for (int i = 0; i < 46; i++) {
				mlistAlphabet.add(AppData.listAllAlphabet.get(i));
			}
		}
		if (level[1]) {
			for (int i = 46; i < 71; i++) {
				mlistAlphabet.add(AppData.listAllAlphabet.get(i));
			}
		}
		if (level[2]) {
			for (int i = 71; i < AppData.listAllAlphabet.size(); i++) {
				mlistAlphabet.add(AppData.listAllAlphabet.get(i));
			}
		}
	}

	private String getListRandom(List<String> list) {
		return list.get(r.nextInt(list.size()));
	}

	private Alphabet getAlphabetRandom() {
		return mlistAlphabet.get(r.nextInt(mlistAlphabet.size()));
	}

	// create random 4 answers for user choice.
	private void addListAns() {
		listAnswer = new ArrayList<String>();
		String answer;
		if (menu == 0 || menu == 1) {
			listAnswer.add(mAlphabet.getRomaji());
			for (int i = 0; i < 3; i++) {
				do {
					answer = getAlphabetRandom().getRomaji();
				} while (answer.equals(listAnswer.get(0)));
				listAnswer.add(answer);
			}
		} else if (menu == 2) {
			listAnswer.add(mAlphabet.getKatakana());
			for (int i = 0; i < 3; i++) {
				do {
					answer = getAlphabetRandom().getKatakana();
				} while (answer.equals(listAnswer.get(0)));
				listAnswer.add(answer);
			}
		}
	}

	private boolean compareAnswer(String answer) {
		if (menu == 0 || menu == 1) {
			if (answer.equals(mAlphabet.getRomaji()))
				return true;
			else
				return false;
		} else if (menu == 2) {
			if (answer.equals(mAlphabet.getKatakana()))
				return true;
			else
				return false;
		}
		return false;
	}

	// Prepare view : set question, create random answer
	private void onCreateView() {
		setMyListAlphabet(level);
		mAlphabet = getAlphabetRandom();
		if (menu == 0 || menu == 2) {
			btnQuestion.setText(mAlphabet.getHiragana());
		} else if (menu == 1) {
			btnQuestion.setText(mAlphabet.getKatakana());
		}
		addListAns();
		lstButtonAns = new ArrayList<Button>();
		lstButtonAns.add(btn1);
		lstButtonAns.add(btn2);
		lstButtonAns.add(btn3);
		lstButtonAns.add(btn4);
		for (int i = 0; i < 4; i++) {
			lstButtonAns.get(i).setText(getListRandom(listAnswer));
			listAnswer.remove(lstButtonAns.get(i).getText());
		}
	}

	// Show message "failed" when answer is fail.
	protected void DisplayMessage() {

		tvMessage.setVisibility(TextView.VISIBLE);
		new Thread() {
			public void run() {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
				}
				messageHandler.sendEmptyMessage(0);
			}
		}.start();
	}

	private Handler messageHandler = new Handler() {

		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			tvMessage.setVisibility(TextView.INVISIBLE);
		}
	};

	/* An array of strings to populate dropdownlist */
	String[] change = new String[] { "* Hiragana - Romaji",
			"* Katakana - Romaji", "* Hiragana - Katakana" };

	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.menu_tracnghiem, menu);
		return true;

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_change:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Chuyển đổi?").setIcon(
					android.R.drawable.ic_dialog_alert);
			builder.setItems(change, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					menu = which;
					onCreateView();
				}
			});
			builder.show();
			break;
		case android.R.id.home:
			Intent intentHome = new Intent(this, MainActivity.class);
			startActivity(intentHome);
			finish();
			break;
		case R.id.menu_level:

			final CharSequence[] items = { "Sơ cấp - Level1",
					"Trung cấp - Level 2", "Cao cấp - Level 3" };
			AlertDialog.Builder builder2 = new AlertDialog.Builder(this);
			builder2.setTitle("Chọn cấp độ")
					.setMultiChoiceItems(items, level,
							new DialogInterface.OnMultiChoiceClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which, boolean isChecked) {
									level[which] = isChecked;
								}
							})
					.setPositiveButton("Đồng ý",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int item) {
									onCreateView();
								}
							});
			builder2.show();

		case R.id.menu_setting:
			PopupMenu popup = new PopupMenu(this, (View) item);
			MenuInflater inflater = popup.getMenuInflater();
			inflater.inflate(R.menu.menu_subsetting, popup.getMenu());
			popup.show();
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	public void showMenu(View v) {
		PopupMenu popup = new PopupMenu(this, v);
		MenuInflater inflater = popup.getMenuInflater();
		inflater.inflate(R.menu.menu_hocchucai, popup.getMenu());
		popup.show();
	}
}
